"""
KidsBuddy 1.0 日志配置
配置系统的日志记录行为
"""

import sys
import os
from loguru import logger
from pathlib import Path

from .settings import LOG_DIR, LOG_LEVEL, LOG_ROTATION, LOG_RETENTION


def setup_logging():
    """配置日志系统"""
    # 确保日志目录存在
    os.makedirs(LOG_DIR, exist_ok=True)
    
    # 清除默认处理器
    logger.remove()
    
    # 添加控制台处理器
    logger.add(
        sys.stdout,
        format="<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>",
        level=LOG_LEVEL,
        colorize=True
    )
    
    # 添加文件处理器
    logger.add(
        str(LOG_DIR / "kidsbuddy_{time}.log"),
        format="{time:YYYY-MM-DD HH:mm:ss.SSS} | {level: <8} | {name}:{function}:{line} - {message}",
        rotation=LOG_ROTATION,
        retention=LOG_RETENTION,
        level=LOG_LEVEL,
        encoding="utf-8"
    )
    
    # 添加错误文件处理器（仅记录错误和更高级别）
    logger.add(
        str(LOG_DIR / "error_{time}.log"),
        format="{time:YYYY-MM-DD HH:mm:ss.SSS} | {level: <8} | {name}:{function}:{line} - {message}",
        rotation=LOG_ROTATION,
        retention=LOG_RETENTION,
        level="ERROR",
        encoding="utf-8"
    )
    
    logger.info("日志系统已初始化")
    
    return logger


# 记录未捕获的异常
def handle_exception(exc_type, exc_value, exc_traceback):
    """处理未捕获的异常"""
    # 忽略KeyboardInterrupt异常的日志记录
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return
        
    logger.opt(exception=(exc_type, exc_value, exc_traceback)).critical("未捕获的异常")


# 设置未捕获异常处理器
sys.excepthook = handle_exception